package app.v1.common.service.impl;

import app.v1.common.domain.ao.dict.DictCreateAo;
import app.v1.common.domain.ao.dict.DictListAo;
import app.v1.common.domain.ao.dict.DictUpdateAo;
import app.v1.common.domain.pojo.Dict;
import app.v1.common.domain.vo.dict.DictListVo;
import app.v1.common.service.DictService;
import com.gitee.feizns.quickstart.domain.web.PageAo;
import com.gitee.feizns.quickstart.domain.web.PageRecordsVo;
import com.gitee.feizns.quickstart.web.ex.NotFoundException;
import com.gitee.feizns.quickstart.web.restful.Rests;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典实现服务
 * @author feizns
 * @since 2023/06/10
 */
@Service
public class DictServiceImpl implements DictService {

    @Override
    public PageRecordsVo<DictListVo> page(PageAo page, DictListAo ao) {
        return Rests.page(Dict.class, page, ao).map(item -> item.copyPropertiesTo(DictListVo.class));
    }

    @Override
    public Dict getById(Long id) {
        return Rests.getById(Dict.class, id);
    }

    @Override
    public Dict updateById(Long id, DictUpdateAo ao) {
        return Rests.patchById(ao.copyPropertiesTo(Dict.class), id);
    }

    @Override
    public Dict deleteById(Long id) {
        Dict dict = Rests.getById(Dict.class, id);
        if ( !dict.isWritable() )
            throw new UnsupportedOperationException(String.format("字典['%s']不支持删除.", dict.getKey()));
        return Rests.deleteById(Dict.class, id);
    }

    @Override
    public Object get(String key) {
        Dict.DictValue value = Dict.value(key);
        if ( value.isNull() )
            throw new NotFoundException("字典'%s'不存在.", key);
        return value.raw();
    }

    @Override
    public Object put(String key, String value) {
        return Dict.put(key, value).value().raw();
    }

    @Override
    public Dict create(DictCreateAo ao) {
        return Rests.create(Dict.class, ao);
    }

    @Override
    public List<Dict> getByType(String type) {
        return new Dict().setType(type).selectList();
    }

    @Override
    public List<Dict> listOfDict(PageAo page, DictListAo ao) {
        return Rests.page(Dict.class, page, ao).getRecords();
    }

}
